$(function() {
	
	//验证
	validateInit();
	
	$('#roleMenuTable').bootstrapTable({
		data : getDatas(),
		striped : true, 
		cache : false, 
		pagination : true, 
		sortable : false, 
		toolbar : "#roleToolbar",
		sidePagination : "client",
		pageNumber : 1,
		pageSize : 10,
		pageList : [ 10, 25, 50, 100 ], 
		search : true, 
		strictSearch : false,
		showColumns : true, 
		clickToSelect : true,
		uniqueId : 'id',
		columns : [ 
		{
			field : 'roleName',
			title : '角色名'
		}, {
			field : 'roleMenus',
			title : '所有权限'
		}, {
			field : 'operate',
			title : '操作'
		}]
	});
	
	$("#roleMenuTable").bootstrapTable("hideColumn","id");
});

function validateInit() {

	
	 
}

function getDatas() {
	var roles;
	$.ajax({
		url: "../role/getAllRoles.action",
		type: "post",
		async: false,//是为了内层ajax在之后访问
		success: function(data) {
			$(data).each(function(){
				//操作赋值
				var roleId = this.id;
				
				this.roleMenus = getRoleMenus(roleId);
				this.operate='<button class=\'btn btn-primary btn-xs\' onclick=\'roleMenu(' + this.id + ')\'>授权</button>&nbsp;'
				 		+	'<button class=\'btn btn-danger btn-xs\' onclick=\'clearRoleMenu(' + this.id + ')\'>清除所有</button>';
			});
			roles = data;
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
	return roles.reverse();
}
function getRoleMenus(roleId) {
	var result = '';
	var roleMenus = [];
	$.ajax({
		url: "../roleMenu/query.action",
		type: "post",
		async: false,
		data: {"roleId": roleId},
		success: function (data) {
			$(data).each(function(){
				var menuId = this.menuId;
				$.ajax({
					url: "../menu/query.action",
					type: "post",
					async: false,
					data: {"id": menuId},
					success: function (data) {
						roleMenus.push(data[0]);
					},
					error: function() {
						toastr.error("获取权限信息出错，请联系管理员");
					}
				});
			});
		},
		error: function() {
			toastr.error("获取角色权限信息出错，请联系管理员");
		}
	});
	if (roleMenus.length == 0) {
		return 'null';
	}
	result = getRecursionMenuName(roleMenus, -1);
	return result;
}

var brCounts = 9999;
var isDataInterface = false;
function getRecursionMenuName(data, pid) {
	var result = '';
	   
    for (var i = 0; i < data.length; i++) {
        if (data[i].parentMenuId == pid && data[i].menuType == '20171026000004') {
        	var myBr = '';
        	if (data[i].menuLevel != brCounts) {
        		brCounts = data[i].menuLevel;
        		for (var j = 0; j < brCounts-1; j++) {
        			myBr += '&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp';
        		}
        	}
        	result += myBr + data[i].menuName;
            var subMenu = getRecursionMenuName(data, data[i].id);
            if (subMenu.length == '') {
            	result += '、';
            } else {
            	subMenu = wipeOff(subMenu);
            	result += '<br/>' + subMenu + '<br/>';
            }
        }
    }
    return  wipeOff(result);
}
function wipeOff(subMenu) {
	if (subMenu[subMenu.length-1] == '、') {
		subMenu = subMenu.substring(0, subMenu.length-1);
	}
	return subMenu;
}

function roleMenu(roleId) {
	$.ajax({
		url: "../menu/query.action",
		type: "post",
		async: false,
		success: function(data) {
			var menuIds = [];
			$.ajax({
				url: "../roleMenu/query.action",
				type: "post",
				async: false,
				data: {"roleId": roleId},
				success: function (data) {
					$(data).each(function(){
						menuIds.push(this.menuId);
					});
				},
				error: function() {
					toastr.error("获取角色权限信息出错，请联系管理员");
				}
			});
			console.log(menuIds);
			var treeViewData = recursion(data, -1, menuIds);
			//console.log(treeViewData);
			$("#treeViewArea").treeview({
				color:"#428bca",
		        showCheckbox: true,
				data: treeViewData,
				onNodeChecked: function(event, node) {
					//console.log(node);
					nodeChecked(event, node);
				},
				onNodeUnchecked: function(event, node) {
					nodeUnchecked(event,node);
				}
            });
		},
		error: function() {
			toastr.error("获取角色信息出错，请联系管理员");
		}
	});
	$("#roleMenuModal .btn-primary").attr("onclick", "saveRoleMenu("+roleId+")");
	$("#roleMenuModal").modal("show");
}

 
function saveRoleMenu(roleId) {
	var menuIds = $("#treeViewArea").treeview('getChecked');
	
	if (menuIds.length == 0) {
		toastr.error("请求失败，至少授权一条菜单");
		$("#roleMenuModal").modal("hide");
		return;
	}
	var roleMenus = new Array();
	$(menuIds).each(function(){
		var roleMenu = {"roleId": roleId,"menuId": this.id};
		roleMenus.push(roleMenu);
	});
	//console.log(JSON.stringify(roleMenus));
	$.ajax({
		url: "../roleMenu/save.action",
		type:"post",
		data: JSON.stringify(roleMenus),
		contentType: "application/json; charset=UTF-8",
		success: function(data) {
			if (data.success=="true") {
				toastr.success("授权成功");
				$("#roleMenuModal").modal("hide");
				$('#roleMenuTable').bootstrapTable("load", getDatas());
			}else {
				toastr.error("后台处理发生错误，请联系管理员");
			}
		},
		error: function() {
			toastr.error("授权请求发送失败，请联系管理员");
		}
	});
}

function clearRoleMenu(roleId) {
	//检查该角色是否拥有权限
	var isIllegal = false;
	$.ajax({
		url: "../roleMenu/query.action",
		type: "post",
		data: {"roleId": roleId},
		async: false,
		success: function(data) {
			if (data.length == 0) {
				toastr.error("该角色无任何权限，不需要清除");
			} else {
				isIllegal = true;
			}
		},
		error: function() {
			toastr.error("检查角色权限出错，请联系管理员");
		}
	});
	
	if (!isIllegal) {
		return;
	}
	swal({
        title: "您确定要清除该角色所有权限吗",
        text: "清除后该角色用户将无法进入任何菜单，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "清除",
        closeOnConfirm: false
    }, function () {
    	$.ajax({
    		url: "../roleMenu/clearRoleMenu.action",
    		type: "post",
    		data: {"roleId":roleId},
    		success: function(data) {
    			if (data == "true") {
    				swal("清除成功", "您已经永久清除了该角色的授权。", "success");
    				$('#roleMenuTable').bootstrapTable("load", getDatas());
    			} else {
    				swal("清除失败", "后台业务处理发生错误，请联系管理员", "error");
    			}
    		},
    		error: function() {
    			swal("操作失败", "提交请求发生错误，请联系管理员。", "error");
    		}
    	});
    });
}

function recursion(data, pid, menuIds) {
	
	
	var result = [];
	   
    for (var i = 0; i < data.length; i++) {
        if (data[i].parentMenuId == pid) {
            var node = '';
            var isNeedChecked = $.inArray(data[i].id, menuIds);
            if (isNeedChecked != -1) {
            	node = {
            		"text": data[i].menuName,
            		"id": data[i].id,
            		"state" : {"checked" : true}
            	};
            } else {
            	node = {
                		"text": data[i].menuName,
                		"id": data[i].id
                };
            }
            var nodes = recursion(data, data[i].id, menuIds);
            if (nodes.length > 0) {
                node.nodes = nodes;
            }
            result.push(node);
        }
    }
    return result;
}



var nodeCheckedSilent = false;  
function nodeChecked (event, node){  
    if(nodeCheckedSilent){  
        return;  
    }  
    nodeCheckedSilent = true;  
    checkAllParent(node);  
    checkAllSon(node);  
    nodeCheckedSilent = false;  
}  
  
var nodeUncheckedSilent = false;  
function nodeUnchecked  (event, node){  
    if(nodeUncheckedSilent)  
        return;  
    nodeUncheckedSilent = true;  
    uncheckAllParent(node);  
    uncheckAllSon(node);  
    nodeUncheckedSilent = false;  
}  
  
//选中全部父节点  
function checkAllParent(node){  
    $('#treeViewArea').treeview('checkNode',node.nodeId,{silent:true});  
    var parentNode = $('#treeViewArea').treeview('getParent',node.nodeId);  
    if(!("nodeId" in parentNode)){  
        return;  
    }else{  
        checkAllParent(parentNode);  
    }  
}  
//取消全部父节点  
function uncheckAllParent(node){  
    $('#treeViewArea').treeview('uncheckNode',node.nodeId,{silent:true});  
    var siblings = $('#treeViewArea').treeview('getSiblings', node.nodeId);  
    var parentNode = $('#treeViewArea').treeview('getParent',node.nodeId);  
    if(!("nodeId" in parentNode)) {  
        return;  
    }  
    var isAllUnchecked = true;  //是否全部没选中  
    for(var i in siblings){  
        if(siblings[i].state.checked){  
            isAllUnchecked=false;  
            break;  
        }  
    }  
    if(isAllUnchecked){  
        uncheckAllParent(parentNode);  
    }  
  
}  
  
//级联选中所有子节点  
function checkAllSon(node){  
    $('#treeViewArea').treeview('checkNode',node.nodeId,{silent:true});  
    if(node.nodes!=null&&node.nodes.length>0){  
        for(var i in node.nodes){  
            checkAllSon(node.nodes[i]);  
        }  
    }  
}  
//级联取消所有子节点  
function uncheckAllSon(node){  
    $('#treeViewArea').treeview('uncheckNode',node.nodeId,{silent:true});  
    if(node.nodes!=null&&node.nodes.length>0){  
        for(var i in node.nodes){  
            uncheckAllSon(node.nodes[i]);  
        }  
    }  
}  
